"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { Label } from "@/components/ui/label"
import { Progress } from "@/components/ui/progress"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { CheckCircle, XCircle } from "lucide-react"
import { vocabularyGrammarQuestions } from "@/lib/questions-data"
import { useUser } from "@/lib/user-context"
import { useToast } from "@/components/ui/use-toast"

export default function VocabularyGrammarPage() {
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0)
  const [selectedOption, setSelectedOption] = useState<string | null>(null)
  const [isAnswered, setIsAnswered] = useState(false)
  const [isCorrect, setIsCorrect] = useState(false)
  const [score, setScore] = useState(0)
  const [wrongAnswers, setWrongAnswers] = useState<any[]>([])
  const router = useRouter()
  const { user } = useUser()
  const { toast } = useToast()

  const currentQuestion = vocabularyGrammarQuestions[currentQuestionIndex]
  const progress = ((currentQuestionIndex + 1) / vocabularyGrammarQuestions.length) * 100

  // 如果用户未登录，重定向到首页
  useEffect(() => {
    if (!user) {
      toast({
        title: "请先登录",
        description: "您需要登录后才能进行练习",
        variant: "destructive",
      })
      router.push("/")
    }
  }, [user, router, toast])

  // 检查答案
  const checkAnswer = () => {
    if (!selectedOption) return

    const isAnswerCorrect = selectedOption === currentQuestion.correctAnswer
    setIsCorrect(isAnswerCorrect)
    setIsAnswered(true)

    if (isAnswerCorrect) {
      setScore(score + 1)
    } else {
      // 添加到错题本
      const wrongAnswer = {
        ...currentQuestion,
        userAnswer: selectedOption,
      }
      setWrongAnswers([...wrongAnswers, wrongAnswer])

      // 保存到本地存储
      const storedWrongAnswers = JSON.parse(localStorage.getItem("wrongAnswers") || "[]")
      localStorage.setItem("wrongAnswers", JSON.stringify([...storedWrongAnswers, wrongAnswer]))
    }
  }

  // 下一题
  const nextQuestion = () => {
    if (currentQuestionIndex < vocabularyGrammarQuestions.length - 1) {
      setCurrentQuestionIndex(currentQuestionIndex + 1)
      setSelectedOption(null)
      setIsAnswered(false)
    } else {
      // 保存进度
      const progress = {
        vocabularyGrammar: {
          completed: true,
          score: score,
          total: vocabularyGrammarQuestions.length,
        },
      }

      const storedProgress = JSON.parse(localStorage.getItem("progress") || "{}")
      localStorage.setItem("progress", JSON.stringify({ ...storedProgress, ...progress }))

      // 显示完成信息
      toast({
        title: "练习完成！",
        description: `您的得分：${score}/${vocabularyGrammarQuestions.length}`,
      })

      // 跳转到结果页面
      router.push(
        "/practice/result?type=vocabulary-grammar&score=" + score + "&total=" + vocabularyGrammarQuestions.length,
      )
    }
  }

  if (!user) {
    return null
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="mb-8">
        <h1 className="text-2xl font-bold mb-4">词汇与语法练习</h1>
        <Progress value={progress} className="h-2" />
        <p className="text-sm text-muted-foreground mt-2">
          问题 {currentQuestionIndex + 1} / {vocabularyGrammarQuestions.length}
        </p>
      </div>

      <Card className="mb-6">
        <CardHeader>
          <CardTitle>问题 {currentQuestionIndex + 1}</CardTitle>
        </CardHeader>
        <CardContent>
          <p className="mb-4 text-lg">{currentQuestion.question}</p>

          <RadioGroup value={selectedOption || ""} onValueChange={setSelectedOption} className="space-y-3">
            {currentQuestion.options.map((option) => (
              <div
                key={option.id}
                className={`flex items-center space-x-2 rounded-md border p-3 ${
                  isAnswered && option.id === currentQuestion.correctAnswer
                    ? "border-green-500 bg-green-50 dark:bg-green-900/20"
                    : isAnswered && option.id === selectedOption
                      ? "border-red-500 bg-red-50 dark:bg-red-900/20"
                      : ""
                }`}
              >
                <RadioGroupItem value={option.id} id={`option-${option.id}`} disabled={isAnswered} />
                <Label htmlFor={`option-${option.id}`} className="flex-1 cursor-pointer">
                  {option.id}. {option.text}
                </Label>
                {isAnswered && option.id === currentQuestion.correctAnswer && (
                  <CheckCircle className="h-5 w-5 text-green-500" />
                )}
                {isAnswered && option.id === selectedOption && option.id !== currentQuestion.correctAnswer && (
                  <XCircle className="h-5 w-5 text-red-500" />
                )}
              </div>
            ))}
          </RadioGroup>

          {isAnswered && (
            <Alert className={`mt-4 ${isCorrect ? "border-green-500" : "border-red-500"}`}>
              <AlertTitle>{isCorrect ? "回答正确！" : "回答错误"}</AlertTitle>
              <AlertDescription>{currentQuestion.explanation}</AlertDescription>
            </Alert>
          )}
        </CardContent>
        <CardFooter className="flex justify-between">
          {!isAnswered ? (
            <Button onClick={checkAnswer} disabled={!selectedOption}>
              提交答案
            </Button>
          ) : (
            <Button onClick={nextQuestion}>
              {currentQuestionIndex < vocabularyGrammarQuestions.length - 1 ? "下一题" : "完成"}
            </Button>
          )}
        </CardFooter>
      </Card>
    </div>
  )
}

